from PySide6.QtWidgets import QDialog,QMessageBox
from sqlalchemy.orm import Session
from settings.publicvar import engine
from views.furtherstudy.model.furtherstudy import FurtherStudy
from views.person.model.person import PersonBaseInfo

from views.furtherstudy.addviewchangefurtherstudydialog import Ui_furtherstudy
from PySide6.QtCore import QDate
import datetime

class AddViewChangeFurtherStudyView(QDialog,Ui_furtherstudy):
    def __init__(self,is_state,data):
        super().__init__()
        self.setupUi(self)
        self.if_state(is_state)
        self.load_form_Structure(data)

        self.savebtn.clicked.connect(self.addItem)
        self.changebtn.clicked.connect(self.changeItem)
        self.name.editingFinished.connect(self.nameFinishedFun)


    # 表单结构
    def load_form_Structure(self,data):
        if data != '':
            self.idx.setText(data[0])
            self.name.setText(data[1])
            date = QDate.fromString(data[2], "yyyy-MM-dd")
            if date.isValid():
                self.start_date.setDate(date)
            else:
                self.start_date.setDate(QDate(1, 1, 1))
                self.start_date.setSpecialValueText("请选择日期")
            self.start_date.setDate(date)
            date = QDate.fromString(data[2], "yyyy-MM-dd")
            if date.isValid():
                self.end_date.setDate(date)
            else:
                self.end_date.setDate(QDate(1, 1, 1))
                self.end_date.setSpecialValueText("请选择日期")
            self.end_date.setDate(date)
            self.school.setText(data[4])
            self.mark.setText(data[5])

    # 查看状态
    def if_state(self,is_state):
        if is_state == 'add':
            self.IDcard.setText('身份证')
            self.name.setPlaceholderText('请输入身份证号')
            self.changebtn.hide()
        elif is_state == 'view':
            self.titlelabel.setText('查看进修信息')
            self.name.setDisabled(True)
            self.savebtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()
        elif is_state == 'change':
            self.titlelabel.setText('修改进修信息')
            self.name.setDisabled(True)
            self.savebtn.hide()
        else:
            self.titlelabel.setText('删除进修信息')
            self.savebtn.hide()

    def get_from_data(self):
        idx = self.idx.text()
        start_date = self.start_date.date()
        start_date = datetime.date(start_date.year(),start_date.month(),start_date.day())
        end_date = self.end_date.date()
        end_date = datetime.date(end_date.year(),end_date.month(),end_date.day())
        school = self.school.text()
        mark = self.mark.text()

        if school == '':
            QMessageBox.critical(None,'空值','输入的数据不能为空')
        data = {'start_date':start_date,'end_date':end_date,'school':school,'mark':mark}
        return (idx,data)

    def addItem(self):
        data = self.get_from_data()
        data[1]['name_id']=self.name_id
        with Session(engine) as session,session.begin():
            furtherstudy = FurtherStudy(**data[1])
            session.add(furtherstudy)
        self.close()

    def changeItem(self):
        data = self.get_from_data()
        with Session(engine) as session, session.begin():
            session.query(FurtherStudy).filter(FurtherStudy.id == data[0]).update(data[1])
            self.close()

    def deleteItem(self):
        data = self.get_from_data()
        with Session(engine) as session,session.begin():
            session.query(FurtherStudy).filter(FurtherStudy.id  == data[0]).delete()

    def nameFinishedFun(self):
        IDcard = self.name.text().strip()
        with Session(engine) as session, session.begin():
            try:
                personbase = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard == IDcard).one()
                if personbase.furtherstudys == []:
                    self.name.setText(personbase.name)
                    self.name_id = personbase.id
                else:
                    QMessageBox.critical(None, '失败', '数据已经增加了，不用添加！')
                    self.close()
            except:
                QMessageBox.critical(None, '失败', '没有找到基本信息，请选增加基本信息,请检查身份证是否输错！')